//
//  RecentSearchDB.swift
//  FeastBooking
//
//  Created by Imon on 2017/12/2.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import FMDB
import JMessage

final class RecentSearchDB: NSObject {
    
    static private var share: RecentSearchDB?
    
    var queue: FMDatabaseQueue?
    
    override init() {
        super.init()
        createDB()
    }
    
    static func getShareInstance() -> RecentSearchDB {
        if share != nil {
            return share!
        } else {
            share = RecentSearchDB()
            return share!
        }
    }
    
    static func logoutInstance() {
        share = nil
    }
    
    private func createDB() {
        let user = JMSGUser.myInfo()

        var dir = "recentSearch"
        if user.username.isEmpty {
            dir += "nouser"
        } else {
            dir += user.username
        }
        
        var path = "\(NSHomeDirectory())/Documents/\(dir)"
        
        if createPath(path) {
            path = path + "/RecentSearch.db"
            queue = FMDatabaseQueue(path: path)
            
            let sql = "create table IF NOT EXISTS RecentSearch(id integer primary key autoincrement, search text)"
            queue?.inDatabase { (db) in
                db?.executeUpdate(sql, withArgumentsIn: nil)
            }
        }
    }
    
    func dropTable() {
        if queue == nil {
            createDB()
        }
        let sql = "drop table if exists RecentSearch"
        queue?.inDatabase { (db) in
            db?.executeUpdate(sql, withArgumentsIn: nil)
        }
    }
    
    func insertData(_ search: RecentSearch) {
        if queue == nil {
            createDB()
        }
        
        let sql = "insert into RecentSearch(search) values ('\(search.search)')"
        
        queue?.inDatabase{ (db) in
            db?.executeUpdate(sql, withArgumentsIn: nil)
        }
        
        if count() > 10 {
            let sql = "delete from RecentSearch where id = (select min(id) from RecentSearch)"
            queue?.inDatabase{ (db) in
                db?.executeUpdate(sql, withArgumentsIn: nil)
            }
        }
    }
    
    func quaryData() -> [RecentSearch] {
        if queue == nil {
            createDB()
        }
        var searches: [RecentSearch] = []
        let sql = "select distinct search from RecentSearch order by id desc"
        queue?.inDatabase { (db) in
            let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
            while (resultSet?.next())! {
                let search = RecentSearch(search: (resultSet?.string(forColumn: "search"))!)
                searches.append(search)
            }
        }
        return searches
    }
    
    func count() -> Int {
        if queue == nil {
            createDB()
        }
        var count: Int = 0
        let sql = "select count(id) as count from RecentSearch"
        queue?.inDatabase { (db) in
            let resultSet = db?.executeQuery(sql, withArgumentsIn: nil)
            if (resultSet?.next())! {
                count = Int((resultSet?.int(forColumn: "count"))!)
            }
        }
        return count
    }
    
    // MARK: - private func
    private func createPath(_ path: String) -> Bool {
        var isDir: ObjCBool = ObjCBool(false)
        
        if FileManager.default.fileExists(atPath: path, isDirectory: &isDir) && isDir.boolValue {
            return true
        } else {
            try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            return true
        }
    }
}

